package cn.tedu.jdbc;

import java.sql.*;
import java.util.Scanner;

/**
 * @Author: Miyako
 * @Date: 2024-07-30-17:19
 * @Description: 使用预编译sql实现预防sql攻击
 */
public class JDBCLogin02 {
    public static void main(String[] args) {
        try(Connection c = new DBUtil().getConnection()){
            Statement statement = c.createStatement();
            Scanner sc = new Scanner(System.in);
            System.out.println("输入你的用户名");
            String username = sc.nextLine();
            System.out.println("输入你的密码");
            String password = sc.nextLine();

            String sql = "Select nickname ,vip from userinfo where username=? and password = ?";
            //使用预编译sql
            PreparedStatement ps = c.prepareStatement(sql);
            //数据库会直接把输入的字符串整个当成数据去执行而不是通过拼接字符串得到的sql指令传入数据库
            ps.setString(1,username);
            ps.setString(2,password);
            ResultSet resultSet = ps.executeQuery();
            String string=null;
            String state = "0";
            resultSet.next() ;

            if (!resultSet.next())
                System.out.println("用户或密码错误，没找到这个用户");
            else {
                string = resultSet.getString("nickname");
                state = resultSet.getString("vip");
                if ("1".equals(state))
                    System.out.println("欢迎尊贵的"+string+"vip会员用户登录！");
                else
                    System.out.println("欢迎普通的"+string+"不是vip会员的穷鬼登录！");
            }

        }catch (SQLException e){
            e.printStackTrace();
        }
    }
}
